package cn.ug.pay.web.controller;

import cn.ug.aop.RequiresPermissions;
import cn.ug.bean.base.DataTable;
import cn.ug.bean.base.Order;
import cn.ug.bean.base.Page;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.config.Config;
import cn.ug.core.SerializeObjectError;
import cn.ug.core.login.LoginHelper;
import cn.ug.pay.bean.BillGoldBean;
import cn.ug.pay.bean.EverydaySellGoldBean;
import cn.ug.pay.bean.SellGoldRecordBean;
import cn.ug.pay.service.BillGoldService;
import cn.ug.util.BigDecimalUtil;
import cn.ug.util.ExportExcelUtil;
import cn.ug.util.PaginationUtil;
import cn.ug.util.UF;
import cn.ug.web.controller.BaseController;
import cn.ug.web.controller.ExportExcelController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * 资产收支记录管理
 * @author kaiwotech
 */
@RestController
@RequestMapping("billGold")
public class BillGoldController extends BaseController {

    @Resource
    private BillGoldService billGoldService;

    @Resource
    private Config config;

    @GetMapping(value = "/everyday/sell/list")
    public SerializeObject<DataTable<EverydaySellGoldBean>> listEverydaySellGoldRecords(@RequestHeader String accessToken, Page page, String payDate) {
        payDate = UF.toString(payDate);
        List<EverydaySellGoldBean> data = billGoldService.queryEverydaySellGoldRecords(payDate);
        if (data != null && data.size() > 0) {
            page.setTotal(data.size());
            if (page.getPageSize() > 0) {
                data = data.stream().skip((PaginationUtil.getPage(page.getPageNum())-1) * page.getPageSize()).limit(page.getPageSize()).collect(Collectors.toList());
            }
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<EverydaySellGoldBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), data));
        } else {
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<EverydaySellGoldBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<EverydaySellGoldBean>()));
        }
    }

    @GetMapping(value = "/everyday/sell/record/list")
    public SerializeObject<DataTable<SellGoldRecordBean>> listBuyGoldRecords(@RequestHeader String accessToken, Page page, String payDate) {
        payDate = UF.toString(payDate);
        int total = billGoldService.countSellGoldRecord(payDate);
        page.setTotal(total);
        if (total > 0) {
            List<SellGoldRecordBean> list = billGoldService.querySellGoldRecord(payDate, PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            for (SellGoldRecordBean bean : list) {
                if (StringUtils.isNotBlank(bean.getMobile())) {
                    bean.setMobile(StringUtils.substring(bean.getMobile(), 0, 3) +"****"+ StringUtils.substring(bean.getMobile(), 7));
                }
            }
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<SellGoldRecordBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<SellGoldRecordBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<SellGoldRecordBean>()));
    }

    @GetMapping(value = "/everyday/sell/record/export")
    public void exportData(HttpServletResponse response, String payDate) {
        payDate = UF.toString(payDate);
        List<SellGoldRecordBean> list = billGoldService.querySellGoldRecord(payDate, 0, 0);
        if(list != null && list.size() > 0){
            String[] columnNames = { "序号", "操作时间","手机号", "用户姓名", "卖出克重（克）", "卖出时金价", "单笔手续费（元/克）", "平台收取手续费（元）", "卖金实际到账金额（元）"};
            String [] columns = {"index",  "payTime", "mobile", "name", "payGram", "goldPrice", "fee", "poundage", "actualAmount"};
            String fileName = "卖金核算详表-"+payDate;
            int index = 1;
            for (SellGoldRecordBean bean : list) {
                bean.setIndex(index);
                index++;
                if (StringUtils.isNotBlank(bean.getMobile())) {
                    bean.setMobile(StringUtils.substring(bean.getMobile(), 0, 3) +"****"+ StringUtils.substring(bean.getMobile(), 7));
                }
            }
            ExportExcelController<SellGoldRecordBean> export = new ExportExcelController<SellGoldRecordBean>();
            export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
        }
    }

    @GetMapping(value = "/everyday/sell/export")
    public void exportStatistics(HttpServletResponse response, String payDate) {
        payDate = UF.toString(payDate);
        List<EverydaySellGoldBean> data = billGoldService.queryEverydaySellGoldRecords(payDate);
        if(data != null && data.size() > 0){
            String[] columnNames = { "序号", "日期","卖金总克重（克）", "平台收取手续费总额（元）", "卖金实际到账总额（元）"};
            String [] columns = {"index",  "payDate", "payGram", "poundage", "actualAmount"};
            String fileName = "卖金核算总表";
            int index = 1;
            for (EverydaySellGoldBean bean : data) {
                bean.setIndex(index);
                index++;
            }
            ExportExcelController<EverydaySellGoldBean> export = new ExportExcelController<EverydaySellGoldBean>();
            export.exportExcel(fileName, fileName, columnNames, columns, data, response, ExportExcelUtil.EXCEL_FILE_2003);
        }
    }


    /**
     * 根据ID查找信息
     * @param id		    ID
     * @return			    记录集
     */
    @RequestMapping(value = "{id}", method = GET)
    public SerializeObject find(@PathVariable String id) {
        if(StringUtils.isBlank(id)) {
            return new SerializeObjectError("00000002");
        }
        BillGoldBean entity = billGoldService.findById(id);
        if(null == entity || StringUtils.isBlank(entity.getId())) {
            return new SerializeObjectError("00000003");
        }
        return new SerializeObject<>(ResultType.NORMAL, entity);
    }

    /**
     * 发起申请
     * @param accessToken		登录成功后分配的Key
     * @param entity		    记录集
     * @return				    是否操作成功
     */
    @RequiresPermissions("pay:billGold:update")
    @RequestMapping(method = POST)
    public SerializeObject update(@RequestHeader String accessToken, BillGoldBean entity) {
        if(null == entity || BigDecimalUtil.isZeroOrNull(entity.getAmount())) {
            return new SerializeObjectError("00000002");
        }
        String memberId = LoginHelper.getLoginId();
        if(StringUtils.isBlank(memberId)) {
            return new SerializeObjectError("00000102");
        }
        entity.setMemberId(memberId);
        billGoldService.save(entity);
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    /**
     * 根据当前登录用户查询数据
     * @param accessToken	    登录成功后分配的Key
     * @param order		        排序
     * @param page		        分页
     * @param type			    类型 0:全部 1:转入 2:转出
     * @param tradeType		    交易类型 0:全部 1:投资活期产品  2:定期转活期 3:存金 4:活期转定期 5:提金 6:卖金
     * @param addTimeMinString	最小操作时间(yyyy-MM-dd)
     * @param addTimeMaxString  最大操作时间(yyyy-MM-dd)
     * @return			        分页数据
     */
    @RequestMapping(value = "queryByMemberId", method = GET)
    public SerializeObject<DataTable<BillGoldBean>> queryByMemberId(@RequestHeader String accessToken, Order order, Page page, Integer type, Integer tradeType, String addTimeMinString, String addTimeMaxString) {
        if(page.getPageSize() <= 0) {
            page.setPageSize(config.getPageSize());
        }
        if(null == type || type < 0) {
            type = 0;
        }
        if(null == tradeType || tradeType < 0) {
            tradeType = 0;
        }
        LocalDateTime addTimeMin = null;
        LocalDateTime addTimeMax = null;
        if(StringUtils.isNotBlank(addTimeMinString)) {
            addTimeMin = UF.getDate(addTimeMinString);
        }
        if(StringUtils.isNotBlank(addTimeMaxString)) {
            addTimeMax = UF.getDate(addTimeMaxString);
        }
        String memberId = LoginHelper.getLoginId();
        if(StringUtils.isBlank(memberId)) {
            return new SerializeObjectError<>("00000102");
        }

        DataTable<BillGoldBean> dataTable = billGoldService.query(order.getOrder(), order.getSort(), page.getPageNum(), page.getPageSize(), type, tradeType,
                null, null, addTimeMin, addTimeMax, memberId, null, null, null);
        return new SerializeObject<>(ResultType.NORMAL, dataTable);
    }

    /**
     * 查询数据
     * @param accessToken	        登录成功后分配的Key
     * @param order		            排序
     * @param page		            分页
     * @param type			        类型 0:全部 1:转入 2:转出
     * @param tradeType		        交易类型 0:全部 1:投资活期产品  2:定期转活期 3:存金 4:活期转定期 5:提金 6:卖金
     * @param amountMin		        最小资产收支记录金额
     * @param amountMax		        最大资产收支记录金额
     * @param addTimeMinString	    最小操作时间
     * @param addTimeMaxString	    最大操作时间
     * @param memberId		        会员ID
     * @param memberName	        会员名称
     * @param memberMobile	        会员手机
     * @param keyword		        关键字
     * @return			            分页数据
     */
    @RequestMapping(method = GET)
    public SerializeObject<DataTable<BillGoldBean>> query(@RequestHeader String accessToken, Order order, Page page, Integer type, Integer tradeType,
                                                          BigDecimal amountMin, BigDecimal amountMax,
                                                          String addTimeMinString, String addTimeMaxString,
                                                          String memberId, String memberName, String memberMobile, String keyword) {
        if(page.getPageSize() <= 0) {
            page.setPageSize(config.getPageSize());
        }
        if(null == type || type < 0) {
            type = 0;
        }
        if(null == tradeType || tradeType < 0) {
            tradeType = 0;
        }
        LocalDateTime addTimeMin = null;
        LocalDateTime addTimeMax = null;
        if(StringUtils.isNotBlank(addTimeMinString)) {
            addTimeMin = UF.getDate(addTimeMinString);
        }
        if(StringUtils.isNotBlank(addTimeMaxString)) {
            addTimeMax = UF.getDate(addTimeMaxString);
        }
        keyword = UF.toString(keyword);

        DataTable<BillGoldBean> dataTable = billGoldService.query(order.getOrder(), order.getSort(), page.getPageNum(), page.getPageSize(), type, tradeType,
                amountMin, amountMax, addTimeMin, addTimeMax, memberId, memberName, memberMobile, keyword);
        return new SerializeObject<>(ResultType.NORMAL, dataTable);
    }
}
